package com.example.gobang.game;

import com.example.gobang.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
@Component
@Data
public class Matcher {
    private Queue<User> normalQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();
    @Autowired
    private onlineUserManager onlineUserManager2;
    public ObjectMapper objectMapper= new ObjectMapper();
    @Autowired
    private RoomManger roomManger;
    @Autowired
    private com.example.gobang.model.UserMapper userMapper;
    public void add(User user){
        if(user.getScore()<2000){
            synchronized (normalQueue){
                normalQueue.offer(user);
                normalQueue.notify();
            }

        }else if(user.getScore()>=2000&&user.getScore()<3000){
            synchronized (highQueue){
                highQueue.offer(user);
                highQueue.notify();
            }

        }else{
            synchronized (veryHighQueue){
                veryHighQueue.offer(user);
                veryHighQueue.notify();
            }
        }
    }
    public void remove(User user){
        if(user.getScore()<2000){
            synchronized (normalQueue){
                normalQueue.remove(user);
            }

        }else if(user.getScore()>=2000&&user.getScore()<3000){
            synchronized (highQueue){
                highQueue.remove(user);
            }

        }else{
            synchronized (veryHighQueue){
                veryHighQueue.remove(user);
            }

        }
    }

    @PostConstruct
    public void Matcher(){
        Thread t1 = new Thread(){
            public void run(){
                while (true){
                    try {
                        handlerMatch(normalQueue);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
        t1.start();
        Thread t2 = new Thread(){
            @Override
            public void run() {
                try {
                    handlerMatch(highQueue);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        t2.start();
        Thread t3 = new Thread(){
            public void run(){
                while (true){
                    try {
                        handlerMatch(veryHighQueue);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };


        t3.start();
    }

    public void handlerMatch(Queue<User> matchQueue) throws IOException, InterruptedException {
        synchronized (matchQueue) {
             while (matchQueue.size() < 2) {
                matchQueue.wait();
            }
            User play1 = matchQueue.poll();
            User play2 = matchQueue.poll();
            System.out.println("匹配出 2 个玩家：" + play1.getUsername() + "," + play2.getUsername());
            WebSocketSession session1 = onlineUserManager2.getFromGameHall(play1.getUserId());
            WebSocketSession session2 = onlineUserManager2.getFromGameHall(play2.getUserId());
            if (session1 == null) {
                matchQueue.offer(play2);
                return;
            }
            if (session2 == null) {
                matchQueue.offer(play1);
                return;
            }
            if (session2 == session1) {
                matchQueue.offer(play2);
                return;
            }
            Room room = new Room();
            // 手动设置依赖，解决自动注入失败的问题
            room.setOnlineUserManager1(onlineUserManager2);
            room.setRoomManger(roomManger);
            room.setUserMapper(userMapper);
            roomManger.add(room,play1.getUserId(),play2.getUserId());
            MatchRequse requse = new MatchRequse();
            requse.setOk(true);
            requse.setMessage("matchSuccess");
            session1.sendMessage(new TextMessage(objectMapper.writeValueAsString(requse)));
            MatchRequse requse2 = new MatchRequse();
            requse2.setOk(true);
            requse2.setMessage("matchSuccess");
            session2.sendMessage(new TextMessage(objectMapper.writeValueAsString(requse2)));

        }
    }



}
